/**
 * @file
 * @auth zhaojing
 * @date 2016/11/21
 */

import Vue from 'vue';
import Pager from '../../../../grsc-base/component/Pager.vue';
import Loading from '../../../../grsc-base/component/Loading.vue';
import NoData from '../../../../grsc-base/component/NoData.vue';
import Tooltip from '../../../../grsc-base/component/Tooltip.vue';
import filter from '../../../../grsc-base/util/filter';
import {
    PAGE_SIZE
} from '../../../../grsc-base/common/constants';
import tpl from './tpl.html';
// import service from './service';
import commonService from '../../../common/commonService';
import symbolConfig from '../../../common/symbolConfig';
import format from '../../../common/format';
import service from './service';
import CONFIG from './config';
import MathTool from '../../../../grsc-base/util/mathtool';

import Deposit from './deposit/main';
import Withdraw from './withdraw/main';
import ForkInfo from '../component/ForkInfo.vue'
import setPayPwd from '../../../component/setPayPwd/main';
import sorttool from '../../../../grsc-base/util/sorttool';

const DO_TYPE_DEPOSIT = 'DEPOSIT';
const DO_TYPE_WITHDRAW = 'WITHDRAW';

export default Vue.extend({
    name: 'Asset',
    template: tpl,
    components: {
        Pager,
        Loading,
        NoData,
        Deposit,
        Withdraw,
        ForkInfo,
        setPayPwd,
        Tooltip
    },
    data() {

        return {
            coinType: '',
            doType: DO_TYPE_DEPOSIT,
            tabType: 'digital',

            list: null,
            fundList: [],
            isLoading: false,
            CONFIG: CONFIG,
            filter: filter,
            condition: {
                pageNo: 1,
                pageSize: PAGE_SIZE
            },
            pageNum: 0,
            isCoin: [],

            assets: {},
            showForkInfo: false,
            forkInfoCoin: '',

            totalBTC: '--',
            totalValue: '--', //总资产
            btcPrice: 0,
            isSetPayPassword: false,
            isShowSetPayPwd: false,
            forkType: '',
            keyCoin: '',
            level: '',
            dfpUsdt: 0,
            hide0Balance: false, //true 隐藏为0的资产
            MYCN: '',
        }
    },
    computed: {

    },
    created() {
        this.getDfp();
        this.getTotalAssets();
        this.fetchPayPsdStatus();
        this.getConfigSymbolRank();
        $(document).off('$$USDCNY').on('$$USDCNY', (event, USDCNY) => {
            this.$USDCNY = USDCNY;
            this.$forceUpdate();
        });
        $(document).off('$$DIGITALUSD').on('$$DIGITALUSD', (event, DIGITALUSD) => {
            this.$DIGITALUSD = DIGITALUSD;
            this.$forceUpdate();
        });
    },
    methods: {


        formatMoney(money, type) {
            if ($.isNumeric(money) === false) {
                return money;
            }
            money = format.formatZeroSuffix(filter.floorFixPrice(money, 8), 8);
            let index = money.indexOf('.');
            let prefix = money.substring(0, index);
            let suffix = money.substring(index + 1);
            if (type === 'GRAY') {
                return '<span class="em">' + prefix + '.</span><em class="em">' + suffix + '</em>';
            }
            return '<span class="strong">' + prefix + '.</span><em class="em">' + suffix + '</em>';
        },

        getCoinDepositWithdrawList() {
            $.when(service.depositAssetList(), service.withdrawAssetList()).done((depositRep, withdrawRep) => {
                this._doCoinList(depositRep.data, withdrawRep.data)
            });
        },

        _doCoinList(depositList, withdrawList) {
            if (depositList) {
                $.map(depositList, (item) => {
                    if (this.assets[item]) {
                        this.assets[item].deposit = true;
                    }
                });
            }

            if (withdrawList) {
                $.map(withdrawList, (item) => {
                    if (this.assets[item]) {
                        this.assets[item].withdraw = true;
                    }
                });
            }
        },

        getTotalAssets() {
            this.isLoading = true;
            // commonService.getBitfinexBtcPrice(),btcPriceRep, 
            $.when(commonService.getTradeDetail(), commonService.getTotalAssets()).done((detailRep, assetRep) => {
                this.isLoading = false;

                // if (btcPriceRep.code === window.CODE.SUCCESS) {
                //     this.btcPrice = btcPriceRep.data.last_price;
                // } else {
                //     window.error(btcPriceRep.msg);
                // }

                if (assetRep.code === window.CODE.SUCCESS) {
                    this._doAssetData(assetRep.data);
                    this._doCurrentPrice(detailRep);
                    commonService.getTradeDetail().done((rep) => {
                        this.MYCN = rep['USDT_MYCN'].newPrice * rep['MYCN_MALL'].newPrice;
                        this._getTotalValue(detailRep);

                    })
                } else {
                    window.error(assetRep.msg);
                }
            });
        },

        getConfigSymbolRank() {
            service.getConfigSymbolRank().done(rep => {
                if (rep.code === window.CODE.SUCCESS) {
                    $.map(rep.data, (item, key) => {
                        if (item.region === 'INNOVATION') {
                            this.isCoin += item.assetCode2;
                        }
                    });
                }
            })
        },


        _doCurrentPrice(data) {
            let that = this;
            $.map(that.assets, (item) => {
                let price = caculateBtcPrice(item, data);

                if (that.assets[item.assetCode]) {
                    that.assets[item.assetCode].price = price;
                }
            });


            function caculateBtcPrice(item, tradeDetailMap) {
                let price = 0;

                if (item.assetCode === 'BTC') { // BTC
                    price = 1;
                    return price;
                }

                if (item.assetCode === 'USDT' || item.assetCode === 'USC') {
                    let tradeObj = tradeDetailMap[item.assetCode + '_BTC'];
                    if (tradeObj && tradeObj.newPrice) {
                        price = MathTool.division(1, tradeObj.newPrice);
                    } else {
                        price = 0;
                    }
                    return price;
                }

                // 如 ACT/BTC
                if (tradeDetailMap['BTC_' + item.assetCode]) {
                    if (tradeDetailMap['BTC_' + item.assetCode]['newPrice']) {
                        price = tradeDetailMap['BTC_' + item.assetCode]['newPrice'];
                    } else {
                        price = 0;
                    }
                    return price;
                }

                // 如 ACT/USDT
                if (tradeDetailMap['USDT_' + item.assetCode]) {
                    if (tradeDetailMap['USDT_' + item.assetCode]['newPrice']) {
                        price = tradeDetailMap['USDT_' + item.assetCode]['newPrice'];
                    } else {
                        price = 0;
                    }
                    return price;
                }

                // 如 ACT/USC
                if (tradeDetailMap['USC_' + item.assetCode]) {
                    if (tradeDetailMap['USC_' + item.assetCode]['newPrice']) {
                        price = tradeDetailMap['USC_' + item.assetCode]['newPrice'];
                    } else {
                        price = 0;
                    }
                    return price;
                }

                // 如 ACT/ETH
                if (tradeDetailMap['ETH_' + item.assetCode]) {
                    if (tradeDetailMap['ETH_' + item.assetCode]['newPrice']) {
                        let ethPrice = tradeDetailMap['ETH_' + item.assetCode]['newPrice'];
                        price = MathTool.multiplication(ethPrice, tradeDetailMap['BTC_ETH']['newPrice']) || 0;
                    } else {
                        price = 0;
                    }
                    return price;
                }

                return price;

            }

        },

        _doAssetData(data) {
            let tmpObj;
            let resultMap = {};
            $.map(this.$$assetMap, (outerItem, key) => {
                $.map(data, (item, index) => {
                    if (item.assetCode === outerItem.assetCode) {
                        tmpObj = $.extend({}, {
                            "amountAvailable": '--',
                            "amountLock": '--',
                            'total': 0,
                            'price': 0,
                            'deposit': false,
                            'withdraw': false,
                            'assetCode': item.assetCode,
                            'status': 'DISQUALIFIED'
                        }, item);
                        tmpObj.total = MathTool.add(item.amountAvailable, item.amountLock);
                        resultMap[item.assetCode] = tmpObj;
                    }
                });
            });

            this.assets = sorttool.sortByStr(resultMap, 'assetCode');
            $.map(this.assets, (item, key) => {
                let data = {
                    asset: item.assetCode
                };
                commonService.getIconList(data).done(rep => {
                    if (rep.data) {
                        Vue.set(item, 'img', rep.data[0].newfilename)
                    } else {
                        Vue.set(item, 'img', '')
                    }
                });
            })
            this.fetchBTCForkStatus();
            this.getCoinDepositWithdrawList();
        },

        _getTotalValue(money) {
            let totalBTC = null;
            let totalValue = 0
            let allAssets = this.assets;
            let USDTNum = 0;
            $.map(allAssets, (item, key) => {
                if ($.isNumeric(item.total) === true) {
                    let moneys = 0;
                    let off = true;
                    if (item.assetCode == 'DFP') {
                        moneys = localStorage.getItem('dfpUsdt');
                        console.log(moneys)
                    }
                    else if (money['USDT_' + item.assetCode]) {
                        moneys = money['USDT_' + item.assetCode].newPrice || 0;
                    } else if (item.assetCode == 'USDT') {
                        moneys = 1;
                    } else if (item.assetCode == 'UDC') {
                        moneys = 1;
                    } else if (item.assetCode == 'DUSD') {
                        moneys = 1;
                    } else if (item.assetCode == 'MALL') {
                        moneys = this.MYCN;
                        console.log(item)
                    } else if (money['UDC_' + item.assetCode]) {
                        moneys = money['UDC_' + item.assetCode].newPrice || 0;
                    } else if (money['DUSD_' + item.assetCode]) {
                        moneys = money['DUSD_' + item.assetCode].newPrice || 0;
                    }
                    moneys = filter.fix(moneys, 6);
                    if (item.assetCode == 'UDC' || money['UDC_' + item.assetCode]) {
                        item.RMB = 6.58 * moneys;
                    } else if (item.assetCode == 'DUSD' || money['DUSD_' + item.assetCode]) {
                        item.RMB = this.$DIGITALUSD * moneys;
                    } else {
                        item.RMB = this.$USDCNY * moneys;
                    }
                    item.RMB = filter.fix(item.RMB, 6);
                    let sum = filter.fix(filter.fix((item.amountAvailable + item.amountLock + item.amountLocking) * item.RMB, 2) / this.$USDCNY, 8);
                    USDTNum += sum * 1;
                }
            });
            this.totalBTC = USDTNum;
            this.totalValue = filter.floorFix(this.totalBTC * this.$USDCNY, 2);

        },


        /**
         * 分页
         * @param pageNo
         */
        changePage(pageNo) {
            this.condition.pageNo = pageNo;
        },


        getDfp() {
            service.getDfp().done(rep => {
                if (rep.code === window.CODE.SUCCESS) {
                    localStorage.setItem('dfpUsdt', rep.data.DFP)
                }
            })
        },

        /**
         * 设置交易密码相关 lanyunlong 2017/12/18
         * */
        setType(coinType, doType, flag) {
            if (flag) {
                this.coinType = coinType;
                if (doType === 'WITHDRAW' && this.isSetPayPassword === false) {
                    this.isShowSetPayPwd = true;
                } else {
                    this.doType = doType;
                    window.location.href = '#/' + doType.toLowerCase() + '/' + coinType;
                }
            }
        },

        fetchPayPsdStatus() {
            commonService.basic().done(rep => {
                if (rep.code === window.CODE.SUCCESS) {
                    this.isSetPayPassword = rep.data.setPayPassword;
                    this.level = rep.data.authLevel;
                } else {
                    window.toast(rep.msg);
                }
            })
        },

        hidSetPayPwd() {
            this.isShowSetPayPwd = false;
        },

        onSetPayPwdSuccess() {
            this.isSetPayPassword = true;
            this.doType = 'WITHDRAW';
            window.location.href = '#/withdraw/' + this.coinType;
        },


        fetchBTCForkStatus() {
            this.fetchForkStatusBySymbol('ACT', 'ABTC'); //abtc改为act的分叉币
        },

        fetchETHForkStatus() {
            // this.fetchForkStatusBySymbol('ETH','EMO');
            // this.fetchForkStatusBySymbol('ETH','ETF');
        },

        fetchLTCForkStatus() {
            // this.fetchForkStatusBySymbol('LTC','LCH');
        },

        /**
         * 查询分叉币种领取状态
         * */
        fetchForkStatusBySymbol(forkAssetCode, targetAssetCode) {
            let param = {
                forkAssetCode,
                targetAssetCode
            };

            service.forkCheck(param).done(rep => {
                if (rep.code === window.CODE.SUCCESS) {
                    if (targetAssetCode === 'ABTC') {
                        this.assets[targetAssetCode].status = rep.data.candyDtoStatus;
                    }
                }
            })
        },


        /**
         * 领取糖果
         * */
        getCandy(forkAssetCode, targetAssetCode) {
            let that = this;
            let param = {
                forkAssetCode,
                targetAssetCode
            };

            service.forkReceive(param).done(rep => {
                if (rep.code === window.CODE.SUCCESS) {
                    window.alert({
                        content: targetAssetCode + that.$t('asset.getSuccess'),
                        btnText: that.$t('common.confirm')
                    });
                    this.getTotalAssets();
                    this.fetchForkStatusBySymbol(forkAssetCode, targetAssetCode);
                } else {
                    window.error(rep.msg);
                }
            })
        },


        /**
         * 展示详细信息
         * */
        forkDetail(coin) {
            this.showForkInfo = true;
            this.forkInfoCoin = coin;
        },

        changeTab(type) {
            this.coinType = '';
            this.keyCoin = '';
            if (type === 'BTC') {
                this.forkType = 'BTC';
                this.fetchBTCForkStatus();
            } else if (type === 'ETH') {
                this.forkType = 'ETH';
                this.fetchETHForkStatus();
            } else if (type === 'LTC') {
                this.forkType = 'LTC';
                this.fetchLTCForkStatus();
            } else {
                this.forkType = '';
            }
            this.tabType = type;
        }
    },

    watch: {}
});